package com.cy.pj.sys.service.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//@Order(1)//数字越小优先级越高，默认优先级最低
@Aspect
@Component
@Slf4j
public class SysCacheAspect {
    //假定一个cache对象,将来可能借助第三方cache产品
    private Map<String,Object> cache=new ConcurrentHashMap<>();//ConcurrentHashMap是线程安全的

    @Pointcut("@annotation(com.cy.pj.common.annotation.RequiredCache)")
    public void doCache(){}

    @Pointcut("@annotation(com.cy.pj.common.annotation.ClearCache)")
    public void doClearCache(){}

    @AfterReturning("doClearCache()")
    public void doAfterReturning(){
        cache.clear();
    }

    @Around("doCache()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint)throws Throwable{
        System.out.println("Get Data from Cache");
        Object result=cache.get("deptkey");//设置一个key，假设从缓存中查数据
        if(result!=null)return result;//存在则返回结果
        //不存在则从数据库查数据
        result=proceedingJoinPoint.proceed();
        System.out.println("Put Data to Cache");
        cache.put("deptkey", result);//把数据存入缓存
        return result;
    }
}
